package cn.springsoter.core.sms.utils;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ResponseUtil {
    private ResponseUtil() {}

    /**
     * 获取post的返回值
     *
     * @param requestBody
     * @param httpUrl
     * @return
     * @throws Exception
     */
    public static JsonNode post(String requestBody, String httpUrl) throws Exception {
        //headers
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json;charset=utf-8");
        //5秒
        int timeout = 5000;
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(timeout);
        requestFactory.setReadTimeout(timeout);
        //HttpEntity
        HttpEntity<String> requestEntity;
        // 设置返回内容默认编码格式
        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
        converters.add(stringHttpMessageConverter);
        RestTemplate restTemplate = new RestTemplate(converters);
        restTemplate.setRequestFactory(requestFactory);

        ResponseEntity<String> responseEntity;
        JsonNode jsonObject = null;
        //解决RestTemplate中headers中添加Host不生效的问题
        System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
        try {
            log.debug("begin invoke url：" + httpUrl + "，requestBody：" + requestBody);
            requestEntity = new HttpEntity<String>(requestBody, requestHeaders);
            responseEntity = restTemplate.postForEntity(httpUrl, requestEntity, String.class);
            jsonObject = JsonUtil.toJsonNode(responseEntity.getBody());

            log.debug(responseEntity.toString());
        } catch (Exception e){
            throw e;
        }
        return jsonObject;
    }
}
